<template>
  <div class="drill">
    <!-- 上方的卡片 -->
    <div class="top">
      <el-card>
        <div class="topLeft">
          <div class="cardTop">
            <div
              :class="{ text2: true, active: mode === 'resAdmin' }"
              @click="clickAdmin"
            >
              资源管理
            </div>
            <div class="line"></div>

            <div
              :class="{ text1: true, active: mode === 'group' }"
              @click="clickGroup"
            >
              分组管理
            </div>
          </div>
          <div class="button">
            <el-button type="primary" @click="beginGroup" v-if="groupShow"
              >新建分组</el-button
            >
            <el-button type="primary" @click="createServer" v-if="!groupShow"
              >添加服务器资源</el-button
            >
          </div>
        </div>

        <div class="topRight">
          <div class="input">
            <el-input
              v-model="search"
              style="width: 400px"
              placeholder="请输入服务器名称..."
            >
              <template #suffix>
                <img src="../../assets/image/放大镜.svg" alt="" /> </template
            ></el-input>
          </div>

          <div class="sign">
            <img src="../../assets/image/感叹号.png" alt="" srcset="" />
            <div class="text">GPU数量标<span>红色</span>为剩余卡</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 下边的服务器 -->
    <div class="down">
      <el-card>
        <div class="tableTop">
          <img src="../../assets/../assets/image/云服务器.png" alt="" />

          <div class="text">已有服务器列表</div>
        </div>

        <div class="downTable">
          <div style="height: 400px; overflow: auto" v-if="!groupShow">
            <el-table
              :data="filterTableData"
              class-name="elTable"
              style="height: 100%"
              :header-cell-style="headerCellStyle"
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="100" />
              </template>
              <el-table-column
                class-name="eltableColumn"
                label="服务器名称"
                prop="name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="IP"
                prop="ip"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU型号"
                prop="GPU_type"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU数量"
                prop="GPU_nmus"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU使用"
                prop="gpu_usage"
              />
              <el-table-column
                class-name="eltableColumn"
                label="内存"
                prop="RAM"
                width="130px"
              />
              <el-table-column
                class-name="eltableColumn"
                label="硬盘"
                prop="ROM"
                width="130px"
              />
              <el-table-column
                class-name="eltableColumn"
                label="分组"
                prop="container_status"
              />
              <!-- <el-table-column label="操作" prop="container_status" /> -->
              <el-table-column align="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    round
                    type="success"
                    @click="handleUpload(scope.$index, scope.row)"
                    >详情</el-button
                  >
                  <el-button
                    size="small"
                    round
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >

                  <el-button
                    size="small"
                    round
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div style="height: 400px; overflow: auto" v-if="groupShow">
            <el-table
              :data="filterTableData"
              class-name="elTable"
              style="height: 100%"
              :header-cell-style="headerCellStyle"
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="100" />
              </template>
              <el-table-column
                class-name="eltableColumn"
                label="组名称"
                prop="container_status"
              />
              <el-table-column
                class-name="eltableColumn"
                label="服务器名称"
                prop="name"
              />
              <el-table-column
                class-name="eltableColumn"
                label="IP"
                prop="ip"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU型号"
                prop="GPU_type"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU数量"
                prop="GPU_nmus"
              />
              <el-table-column
                class-name="eltableColumn"
                label="GPU使用"
                prop="gpu_usage"
              />
              <el-table-column
                class-name="eltableColumn"
                label="内存"
                prop="RAM"
                width="130px"
              />
              <el-table-column
                class-name="eltableColumn"
                label="硬盘"
                prop="ROM"
                width="130px"
              />

              <!-- <el-table-column label="操作" prop="container_status" /> -->
              <el-table-column align="right">
                <template #default="scope">
                  <el-button
                    size="small"
                    round
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >

                  <el-button
                    size="small"
                    round
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 新建分组的弹窗 -->
          <el-dialog v-model="groupShowDialog">
            <template #header>
              <h4>新建分组</h4>
            </template>
            <el-form style="width: 500px; margin-left: 150px" :rules="rules">
              <el-form-item
                label="服务器分组:"
                style="font-weight: bold"
                prop="group_name"
              >
                <el-input placeholder="请输入服务器分组名称" />
              </el-form-item>
            </el-form>
            <!-- <div
              style="border: 1px solid #ccc; width: 100%; margin-top: 60px"
            ></div> -->

            <div slot="footer" style="margin-top: 45px; margin-left: 400px">
              <el-button @click="groupShowDialog = false">取消</el-button>
              <el-button type="primary">确认</el-button>
            </div>
          </el-dialog>

          <!-- 创建服务器的弹窗 -->
          <el-dialog v-model="serverShow" class="serverShow">
            <template #header>
              <h4>服务器资源</h4>
            </template>
            <el-form
              style="margin-right: 150px; margin-left: 150px"
              label-width="90px"
            >
              <el-form-item label="IP:" style="font-weight: bold">
                <el-input placeholder="请输入IP名称" />
              </el-form-item>
            </el-form>
            <el-form
              style="margin-right: 150px; margin-left: 150px; display: flex"
              label-width="90px"
            >
              <el-form-item label="用户名:" style="font-weight: bold">
                <el-input placeholder="请输入用户名" />
              </el-form-item>
              <el-form-item label="密码:" style="font-weight: bold">
                <el-input placeholder="请输入密码" />
              </el-form-item>
            </el-form>

            <div class="backfull">
              <el-button type="primary">自动回填</el-button>
            </div>

            <el-form
              style="margin-right: 150px; margin-left: 150px"
              label-width="100px"
              :rules="rules"
            >
              <el-form-item
                prop="server_name"
                label="服务器名称:"
                style="font-weight: bold"
              >
                <el-input placeholder="请输入服务器名称" />
              </el-form-item>
              <el-form-item
                prop="server_name"
                label="GPU型号:"
                style="font-weight: bold"
              >
                <el-input placeholder="请输入GPU型号" />
              </el-form-item>
              <el-form-item
                prop="server_name"
                label="GPU数量:"
                style="font-weight: bold"
              >
                <el-input placeholder="请输入GPU数量" />
              </el-form-item>
            </el-form>
            <el-form
              style="width: 900px; margin-left: 39px"
              label-width="210px"
              :rules="rules"
            >
              <div style="display: flex; position: relative">
                <el-form-item
                  prop="server_name"
                  label="服务器分组:"
                  style="font-weight: bold"
                >
                  <el-select
                    v-model="form.model"
                    placeholder="请输入服务器分组"
                  >
                    <el-option
                      v-for="(item, index) in imageList"
                      :key="index"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
                <div class="newGroup" style="margin-left: 100px">
                  <el-button type="primary">新建分组</el-button>
                </div>
              </div>
            </el-form>
            <!-- 
          <h4 style="margin-right: 700px; font-weight: bold">配置</h4> -->

            <el-form
              style="width: 500px; margin-left: 100px"
              label-width="130px"
              :rules="rules"
            >
              <el-form-item
                prop="server_name"
                label="CPU:"
                style="font-weight: bold"
              >
                <el-input placeholder="请输入CPU名称" />
              </el-form-item>
              <el-form-item
                prop="server_name"
                label="内存:"
                style="font-weight: bold"
              >
                <el-input placeholder="请输入内存大小" />
              </el-form-item>
              <el-form-item
                prop="server_name"
                label="硬盘:"
                style="font-weight: bold"
              >
                <el-input placeholder="请输入硬盘大小" />
              </el-form-item>
            </el-form>
            <div
              style="border: 1px solid #ccc; width: 100%; margin-top: 60px"
            ></div>

            <div class="footer" style="margin-top: 25px; margin-left: 400px">
              <el-button @click="serverShow = false">取消</el-button>
              <el-button type="primary">确认</el-button>
            </div>
          </el-dialog>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import {
  ElCard,
  ElDialog,
  ElInput,
  ElTable,
  ElTableColumn,
  ElButton,
  ElEmpty,
  ElMessageBox,
  ElMessage,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElCheckbox
} from 'element-plus'
import { reactive, ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { getGather } from '../../api/gather.js'
import { getServerList, getServerListGpu } from '../../api/server.js'

const router = useRouter()

const modelList = ref(['LangPost6'])
const gatherList = ref(['LangPost6'])
const modelList2 = ref(['LangPost6'])

const form = reactive({
  gather: '全部',
  model: '全部'
})
const isCreate = ref(false)

const search = ref('')
const editingRowData = ref({})
const dialogVisible = ref(false) // 编辑回显时的弹窗
let editIndex = -1 // 表示没有编辑的行
const serverShow = ref(false) //创建服务器的弹窗显示

const mode = ref('resAdmin') // 页头的分页切换
const tableData = reactive([
  {
    ip: '',
    name: ''
  }
])

const tableData1 = reactive([
  {
    CPU: '',
    GPU_nmus: '',
    GPU_type: '',
    RAM: '',
    ROM: '',
    gpu_usage: ''
  }
])

const mergedData = reactive([
  {
    ip: '',
    name: '',
    CPU: '',
    GPU_nmus: '',
    GPU_type: [],
    RAM: '',
    ROM: '',
    gpu_usage: ''
  }
])

const server_ip = ref('')
const groupShow = ref(false)
const groupShowDialog = ref(false)

const rules = reactive({
  group_name: [
    { required: true, message: '请输入正确的分组名', trigger: 'blur' }
  ],
  server_name: [
    { required: true, message: '请输入正确的英文名字', trigger: 'blur' },
    {
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/,
      message: '英文名字格式错误 支持英文+数字',
      trigger: 'blur'
    }
  ]
})

// 点击创建服务器
const createServer = () => {
  serverShow.value = true
}

// 新建分组
const beginGroup = () => {
  groupShowDialog.value = true
}

const clickGroup = () => {
  mode.value = 'group'
  groupShow.value = !groupShow.value
}

const clickAdmin = () => {
  mode.value = 'resAdmin'
  groupShow.value = !groupShow.value
}

// 更改el-table行头样式
const headerCellStyle = () => {
  return {
    backgroundColor: '#f6f6f6'
  }
}

// 点击编辑
const handleEdit = (index, row) => {
  editIndex = index
  editingRowData.value = { ...row }
  dialogVisible.value = true
}
//
const handleUpdate = () => {
  if (editIndex !== -1) {
    tableData.splice(editIndex, 1, { ...editingRowData })
    dialogVisible.value = false
    // tableData.value = editingRowData.value  直接赋值会失败,因为直接赋值只是赋值,而这里需要一个对象
    tableData[editIndex] = Object.assign({}, editingRowData.value)

    ElMessage({
      type: 'success',
      message: '恭喜你训练成功 快去部署数据吧'
    })
  } else {
    ElMessage({
      type: 'error',
      message: '修改失败!'
    })
  }
}

// 点击新建服务器
const beginCreate = () => {
  router.push('./createGather')
}

// 搜索功能
const filterTableData = computed(function () {
  return mergedData.filter(function (data) {
    return (
      !search.value ||
      data.container_name.toLowerCase().includes(search.value.toLowerCase())
    )
  })
})

const handleDelete = (index, row) => {
  ElMessageBox.confirm(`您确定要删除模型名称为${row.name}的数据吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      tableData.splice(index, 1)
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {})
}

async function fetchData () {
  try {
    await getServerList().then(res => {
      tableData.length = 0 // 清空tableData数组
      tableData.push(...res.data) // 将返回的数据添加到tableData数组中

      server_ip.value = tableData.map(item => item.ip).join("','")

      getServerListGpu({ server_ip: server_ip.value }).then(response => {
        tableData1.length = 0 // 清空tableData1数组
        tableData1.push(response.data)

        mergedData.length = 0
        for (
          let i = 0;
          i < Math.min(tableData.length, tableData1.length);
          i++
        ) {
          const mergedObj = Object.assign({}, tableData[i], tableData1[i])
          mergedData.push(mergedObj)
          console.log('有ip的服务器列表的mergedData', mergedData)
        }
      })
    })
  } catch (error) {
    console.error('从后台拿现有模型列表失败', error)
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style lang="less" scoped>
.drill {
  display: flex;
  margin: 0 auto;
  flex-direction: column;
  .top {
    padding: 20px 35px 20px 35px;

    :deep(.el-card__body) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 100px;
    }

    .cardTop {
      margin-bottom: 20px;
      color: #b8d5ff;
      font-size: 20px;
      opacity: 0.85;
      display: flex;

      .text1 {
        margin: 0 5px;
      }
      .text2 {
        margin: 0 5px;
      }
      .line {
        width: 2.5px;
        height: 20px;
        background-color: #d7d7d7;
      }
      .text1,
      .text2 {
        cursor: pointer;
      }

      .active {
        color: #267fff;
      }
    }

    .topRight {
      font-weight: bold;

      .input {
        img {
          width: 17px;
          height: 17px;
        }
      }

      .sign {
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: end;
        img {
          width: 20px;
          height: 20px;
        }
        .text {
          margin-left: 5px;
          font-weight: normal;
          color: gray;
          span {
            color: rgb(242, 129, 129);
          }
        }
      }
    }
  }
  .down {
    padding: 0 35px 0 35px;

    :deep(.el-card__body) {
      width: 100%;
      height: 400px;
    }

    .tableTop {
      font-weight: bold;
      display: flex;
      justify-content: center;

      align-items: center;
      height: 40px;

      img {
        width: 70px;
        height: 70px;
      }
      .text {
        font-size: 22px;
        font-weight: bold;
        margin: 10px 0 0 20px;
      }
    }

    .downTable {
      height: 500px;
      width: 100%;
      position: relative;
      img {
        width: 20px;
        height: 20px;
      }
      .elTable {
        position: absolute;
        top: 10%;
        :deep(.eltableColumn) {
          color: black;
          text-align: center;
          height: 52px;
        }
      }
    }
  }
  :deep(.el-dialog) {
    margin-top: 300px;
  }

  // 服务器的弹窗
  .serverShow {
    .backfull {
      ::v-deep(.el-button) {
        width: 40%;
        margin-bottom: 20px;
        margin-left: 77px;
      }
    }

    .footer {
      ::v-deep(.el-button) {
        margin-left: 50px;
      }
    }
  }
  // :deep(.el-dialog__header) {
  //   margin-right: 700px;
  // }
}
</style>
